package com.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.app.conf.RedisService;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.EnterpriseService;
import com.app.service.JobPublishService;
import com.app.service.LiveService;
import com.app.service.LiveVideoService;
import com.app.util.CommonHelp;
import com.app.util.LiveUtils;
import com.app.util.StringTool;
import com.app.vo.LiveVo;
import com.app.vo.WebSocketVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.live.v20180801.models.StopRecordTaskRequest;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Description:直播实现类
 * @Author: N
 * @Date: 2022年11月24日 10点29分
 */
@Service
public class LiveServiceImpl implements LiveService {

    @Autowired
    LiveRecordMapper liveRecordMapper;
    @Autowired
    LiveCompanyMapper liveCompanyMapper;
    @Autowired
    LiveCompanyPostMapper liveCompanyPostMapper;

    @Autowired
    private RedisService redisService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private JobPublishService jobPublishService;
    @Autowired
    private LiveVideoService liveVideoService;

    @Override
    public int liveRecordInsert(LiveRecordModel model) {
        return liveRecordMapper.insert(model);
    }

    @Override
    public int liveCompanyInsert(LiveCompanyModel model) {
        return liveCompanyMapper.insert(model);
    }

    @Override
    public int liveCompanyPostInsert(LiveCompanyPostModel model) {
        return liveCompanyPostMapper.insert(model);
    }

    @Override
    public Object liveEnd(String roomNo) throws TencentCloudSDKException {
        List<LiveRecordModel> liveList = (List<LiveRecordModel>) redisService.getStringKey("yumenLiveList");
        LiveRecordModel liveRecord = null;
        JSONObject company = null;

        for (int i = 0; i < liveList.size(); i++) {
            if (StringTool.isNotEmpty(liveList.get(i).getRoomNo()) && liveList.get(i).getRoomNo().equals(roomNo)) {
                liveRecord = liveList.get(i);
                company = new JSONObject(liveList.get(i));
            }
        }

        if (company != null) {
            if (!company.has("positionData")) {
                LiveRecordModel model = new LiveRecordModel();
                model.setEndTime(CommonHelp.getNowTimestamp());
                model.setCrtTime(CommonHelp.getNowTimestamp());
                model.setRoomNo(liveRecord.getRoomNo());
                model.setRoomName(liveRecord.getRoomName());
                model.setUserId(liveRecord.getUserId());
                model.setCoverUrl(liveRecord.getCoverUrl());
                model.setEndTime(liveRecord.getEndTime());
                model.setRealName(liveRecord.getRealName());
                model.setIntroduce(liveRecord.getIntroduce());
                model.setFaceUrl(liveRecord.getFaceUrl());
                liveRecordInsert(model);
                if (liveList != null) {
                    for (int i = 0; i < liveList.size(); i++) {
                        if (StringTool.isNotEmpty(liveList.get(i).getRoomNo()) && liveList.get(i).getRoomNo().equals(roomNo)) {
                            liveList.remove(i);
                        }
                    }
                    redisService.deleteKey("yumenLiveList");
                    redisService.setStringKey("yumenLiveList", liveList);
                }

                return null;
            } else {
                Map maps = (Map) JSON.parse(company.getString("positionData"));
                LiveRecordModel model = new LiveRecordModel();
                model.setEndTime(CommonHelp.getNowTimestamp());
                model.setCrtTime(CommonHelp.getNowTimestamp());
                model.setRoomNo(liveRecord.getRoomNo());
                model.setRoomName(liveRecord.getRoomName());
                model.setUserId(liveRecord.getUserId());
                model.setCoverUrl(liveRecord.getCoverUrl());
                model.setEndTime(liveRecord.getEndTime());
                model.setRealName(liveRecord.getRealName());
                model.setIntroduce(liveRecord.getIntroduce());
                model.setFaceUrl(liveRecord.getFaceUrl());

                liveRecordInsert(model);
                Map<String, Object> comMap = new HashMap<>();
                for (Object map : maps.entrySet()) {
                    String comId = String.valueOf(((Map.Entry) map).getKey());
                    if (comMap.get(comId) == null) {
                        LiveCompanyModel liveCompany = new LiveCompanyModel();
                        liveCompany.setLiveId(liveRecord.getRoomNo());
                        liveCompany.setEid(Integer.valueOf(comId));
                        liveCompanyInsert(liveCompany);
                        List<String> postIdList = jsonToMap(((Map.Entry) map).getValue().toString());
                        for (int i = 0; i < postIdList.size(); i++) {
                            LiveCompanyPostModel liveCompanyPost = new LiveCompanyPostModel();
                            liveCompanyPost.setCid(liveCompany.getId());
                            liveCompanyPost.setPid(Integer.parseInt(postIdList.get(i)));
                            liveCompanyPostInsert(liveCompanyPost);
                        }
                    } else {
                        List<String> postIdList = jsonToMap(((Map.Entry) map).getValue().toString());
                        for (int i = 0; i < postIdList.size(); i++) {
                            LiveCompanyModel liveCompany = new LiveCompanyModel();
                            LiveCompanyPostModel liveCompanyPost = new LiveCompanyPostModel();
                            liveCompanyPost.setCid(liveCompany.getId());
                            liveCompanyPost.setPid(Integer.parseInt(postIdList.get(i)));
                            liveCompanyPostInsert(liveCompanyPost);
                        }
                    }

                }
                for (int i = 0; i < liveList.size(); i++) {
                    if (StringTool.isNotEmpty(liveList.get(i).getRoomNo()) && liveList.get(i).getRoomNo().equals(roomNo)) {
                        liveList.remove(i);
                    }
                }
            }
            if (liveList != null) {
                for (int i = 0; i < liveList.size(); i++) {
                    if (StringTool.isNotEmpty(liveList.get(i).getRoomNo()) && liveList.get(i).getRoomNo().equals(roomNo)) {
                        liveList.remove(i);
                    }
                }
            }

            redisService.deleteKey("yumenLiveList");
            redisService.setStringKey("yumenLiveList", liveList);
        }
        return null;
    }


    @Override
    public Object getLiveCoverUrlList(String roomNos) {
        String[] str = roomNos.split(",");
        Map<String, String> returnMap = new HashMap<>();
        List<LiveRecordModel> liveList = (List<LiveRecordModel>) redisService.getStringKey("yumenLiveList");
        for (int i = 0; i < str.length; i++) {
            for (int j = 0; j < liveList.size(); j++) {

                if (str[i].equals(liveList.get(j).getRoomNo())) {
                    returnMap.put(liveList.get(j).getRoomNo(), liveList.get(j).getCoverUrl());
                }
            }
        }
        return returnMap;
    }

    @Override
    public Object getLiveAllList(int type, int page, int limit) {
        List<LiveRecordModel> liveList = new ArrayList<>();
        LiveVo vo = new LiveVo();
        int count = 0;
        if (type == 1) {
            liveList = (List<LiveRecordModel>) redisService.getStringKey("yumenLiveList");

            if (liveList != null) {
                for (int i = 0; i < liveList.size(); i++) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String bir = sdf.format(liveList.get(i).getStartTime());
                    liveList.get(i).setFormatTime(bir);
                    List<WebSocketVO> webSocketVOList = (List<WebSocketVO>) redisService.getStringKey(liveList.get(i).getRoomNo());
                    if (webSocketVOList != null) {
                        liveList.get(i).setAudience(webSocketVOList.size() - 1);
                    }
                }
                int size = liveList.size();
                int pageStart = page == 1 ? 0 : (page - 1) * limit;//截取的开始位置
                int pageEnd = size < page * limit ? size : page * limit;//截取的结束位置
                if (size > pageStart) {
                    List<LiveRecordModel> listSort = liveList.subList(pageStart, pageEnd);
                    for (int i = 0; i < listSort.size(); i++) {
                        listSort.get(i).setId(null);
                        listSort.get(i).setUserId(null);
                    }

                    vo.setList(listSort);
                }
                vo.setCount(liveList.size());
            } else {
                vo.setCount(0);
            }
        } else {
            Page<LiveRecordModel> liveRecordModelPage = getModelAll(page, limit);
            liveList = liveRecordModelPage.getRecords();
            count = (int) liveRecordModelPage.getTotal();
            vo.setList(liveList);
            vo.setCount(count);
        }
        return vo;
    }


    @Override
    public Page<LiveRecordModel> getModelAll(int page, int limit) {
        QueryWrapper<LiveRecordModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().orderByDesc("id");
        Page<LiveRecordModel> pages = new Page<>();
        pages.setCurrent(page);
        pages.setSize(limit);
        Page<LiveRecordModel> enterprisePage = liveRecordMapper.selectPage(pages, queryWrapper);
        return enterprisePage;
    }

    @Override
    public Object getLivePostList(String roomNo) {
        List<LiveRecordModel> liveList = (List<LiveRecordModel>) redisService.getStringKey("yumenLiveList");
        LiveRecordModel liveRecord = null;
        JSONObject company = null;
        for (int i = 0; i < liveList.size(); i++) {
            if (StringTool.isNotEmpty(liveList.get(i).getRoomNo()) && liveList.get(i).getRoomNo().equals(roomNo)) {
                liveRecord = liveList.get(i);
                company = new JSONObject(liveList.get(i));
            }
        }
        if (!company.has("positionData")) {
            return null;
        } else {
            Map maps = (Map) JSON.parse(company.getString("positionData"));
            Map<String, Object> comMap = new HashMap<>();
            List<EnterpriseModel> enterpriseModelList = new ArrayList<>();
            for (Object map : maps.entrySet()) {
                String comId = String.valueOf(((Map.Entry) map).getKey());
                if (comMap.get(comId) == null) {
                    EnterpriseModel enterprise = enterpriseService.findModelById(Integer.valueOf(comId));
                    List<String> postIdList = jsonToMap(((Map.Entry) map).getValue().toString());
                    List<JobPublishModel> jobPublishList = new ArrayList<>();
                    for (int i = 0; i < postIdList.size(); i++) {
                        JobPublishModel jobPublishModel = jobPublishService.findAllJobById(Integer.valueOf(postIdList.get(i)));
                        jobPublishList.add(jobPublishModel);
                    }
                    enterprise.setJobPublishList(jobPublishList);
                    enterpriseModelList.add(enterprise);
                    comMap.put(comId, enterprise);

                } else {
                    EnterpriseModel enterprise = (EnterpriseModel) comMap.get(comId);
                    List<JobPublishModel> jobPublishList = enterprise.getJobPublishList();
                    List<String> postIdList = jsonToMap(((Map.Entry) map).getValue().toString());
                    for (int i = 0; i < postIdList.size(); i++) {
                        JobPublishModel jobPublishModel = jobPublishService.findAllJobById(Integer.valueOf(postIdList.get(i)));
                        jobPublishList.add(jobPublishModel);
                    }
                    enterprise.setJobPublishList(jobPublishList);
                    comMap.put(comId, enterprise);

                    enterpriseModelList.add(enterprise);

                }


            }
            return enterpriseModelList;
        }
    }

    @Override
    public Object getEndLive(String roomNo) {
        LiveRecordModel model = getModelByRoomNo(roomNo);
        LiveVideoModel liveVideoModel = liveVideoService.getModelByRoomNo(roomNo);
        String videoUrl = liveVideoModel.getVideoUrl();
        videoUrl = videoUrl.replace("http","https");
        model.setVideoUrl(videoUrl);
        List<LiveCompanyModel> liveCompanyModelList = getLiveCompanyListByRoomNo(roomNo);
        List<EnterpriseModel> enterpriseModelList = new ArrayList<>();
        List<JobPublishModel> jobPublishModelList = new ArrayList<>();
        for (int i = 0; i < liveCompanyModelList.size(); i++) {
            EnterpriseModel enterprise = enterpriseService.findModelById(Integer.valueOf(liveCompanyModelList.get(i).getEid()));
            enterpriseModelList.add(enterprise);
            List<LiveCompanyPostModel> liveCompanyPostlList = getLiveCompanyPostListByCid(liveCompanyModelList.get(i).getId());
            for (int j = 0; j < liveCompanyPostlList.size(); j++) {
                JobPublishModel jobPublishModel = jobPublishService.findAllJobById(liveCompanyPostlList.get(j).getPid());
                jobPublishModel.setEnterprise(enterprise);
                jobPublishModelList.add(jobPublishModel);
            }
        }
        LiveVo vo = new LiveVo();
        vo.setModel(model);
        vo.setCompanyList(enterpriseModelList);
        vo.setPublishList(jobPublishModelList);
        return vo;
    }

    @Override
    public void update(LiveRecordModel model) {

        liveRecordMapper.updateById(model);
    }

    @Override
    public LiveRecordModel getModelByRoomNo(String roomNo) {

        QueryWrapper<LiveRecordModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().eq("room_no", roomNo);
        List<LiveRecordModel> modelList = liveRecordMapper.selectList(queryWrapper);
        if (modelList == null && modelList.isEmpty()) {
            return null;
        } else {
            return modelList.get(0);
        }
    }

    @Override
    public List<LiveCompanyModel> getLiveCompanyListByRoomNo(String roomNo) {
        QueryWrapper<LiveCompanyModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().eq("live_id", roomNo);
        List<LiveCompanyModel> modelList = liveCompanyMapper.selectList(queryWrapper);
        return modelList;
    }

    @Override
    public List<LiveCompanyPostModel> getLiveCompanyPostListByCid(Integer cid) {
        QueryWrapper<LiveCompanyPostModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().eq("cid", cid);
        List<LiveCompanyPostModel> modelList = liveCompanyPostMapper.selectList(queryWrapper);
        return modelList;
    }

    public List<String> jsonToMap(String mapValue) {
        List<String> postIdList = new ArrayList<>();
        if (mapValue.contains(",")) {
            String[] postIds = (mapValue.split(","));
            for (int i = 0; i < postIds.length; i++) {
                postIdList.add(postIds[i]);
            }
        } else {
            String postId = mapValue;
            postIdList.add(postId);
        }
        return postIdList;

    }
}
